-
Notifications
You must be signed in to change notification settings - Fork 0
/
Postfix to Prefix.cpp
50 lines (45 loc) · 1.31 KB
/
Postfix to Prefix.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <iostream>
#include <stack>
using namespace std;
bool isOperand(char data){
return (data >= 'a' && data <= 'z') || (data >= 'A' && data <= 'Z');
}
bool isOperator(char data){
return (data == '+' || data == '-' || data == '*' || data == '/' || data == '^');
}
string prefix(string postfix){
stack<string> stack;
string data;
for(int i = 0; i < postfix.size(); i++){
data = postfix[i];
if(isOperand(data[0])){
stack.push(data);
} else if (isOperator(data[0])){
if(!stack.empty()){
string A, B, sum;
A = stack.top(); stack.pop();
if(stack.empty()){
sum = data + " " + A;
} else {
B = stack.top(); stack.pop();
sum = data + " " + B + " " + A;
}
stack.push(sum);
}
} else {
stack.push("!");
break;
}
}
return (!stack.empty() && stack.top() != "!") ? stack.top() : "!";
}
int main(){
string postfix = "KL+MN*-OP^W*U/V/T*+Q+";
cout << "Postfix: " << postfix << endl;
string result = prefix(postfix);
if(result == "!"){
cout << "INPUT: Invalid Expression!" << endl;
} else {
cout << "Prefix: " << result << endl;
}
}